package com.cdc.sptapi.method;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.cdc.bean.person.FileResult;
import com.cdc.bean.person.Result;
import com.cdc.bean.user.User;
import com.cdc.tools.UserTools;

@RestController
public class MethodUser {
	/**
	 * http://ip:8084/user/123
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/user/{id}", method = {RequestMethod.GET,RequestMethod.POST})
	public User after(@PathVariable("id") Integer id) {
		id=id>4 || id<0 ? 0 :id;
		return UserTools.initUsers().get(id);
	}

	
	/**
	 * http://ip:8084/100/user
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/user", method = {RequestMethod.GET,RequestMethod.POST})
	public User before(@PathVariable("id") Integer id) {
		id=id>4 || id<0 ? 0 :id;
		return UserTools.initUsers().get(id);
	}
	
	/**
	 * http://ip:8084/100/userList
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/userList", method = {RequestMethod.GET,RequestMethod.POST})
	public Map<Integer,User> users() {
		return UserTools.initUsers();
	}
	
	/**
	 * http://ip:8084/100/users
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/users", method = {RequestMethod.GET,RequestMethod.POST})
	public List<User> userList() {
		Map<Integer,User> users=UserTools.initUsers();
		List<User> lists=new ArrayList<>();
		for (User value : users.values()) {  
			lists.add(value); 
		}
		return lists;
	}

	
	/**
	 * http://192.168.0.164:8084/userorigin?id=90
	 * @param idP
	 * @return
	 */
	@RequestMapping(value = "/user", method = {RequestMethod.GET,RequestMethod.POST})
	public User origin(@RequestParam("id") Integer id){
		id=id>4 || id<0 ? 0 :id;
		return UserTools.initUsers().get(id);
	}

	/**
	 * http://192.168.0.164:8084/userdefault?id=90 可以不传id,并且给id设置了默认值
	 * 
	 * @param idP
	 * @return
	 
	@RequestMapping(value = "/userdefault", method = {RequestMethod.GET,RequestMethod.POST})
	public User user(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id) {
		id=id>4 || id<0 ? 0 :id;
		return UserTools.initUsers().get(id);
	}
	*/
	
	/**
	 * http://192.168.0.164:8084/userBoth?id=90&name="cdc"必须传id
	 * 使用postman测试时   需要设置x-www-form-urlencoded类型才能正确返回。
	 * 
	 * @param idP
	 * @return
	 */
	@RequestMapping(value = "/userBoth", method = {RequestMethod.GET,RequestMethod.POST})
	public User userBoth(@RequestParam(value = "id", required = true) Integer id,@RequestParam(value = "name", required = true) String name) {
		id=id>4 || id<0 ? 0 :id;
		User user=UserTools.initUsers().get(id);
		user.setName(name);
		return user;
	}
	
	/**
	 * http://ip:8084/findUser
	 * Springbootm默认使用jackson解析json
	 * @return
	 */
	@RequestMapping("/user")
	public User findUser() {
		User user = UserTools.initDefaultUser();
		return user;
	}
	
	/**
	 * http://ip:8084/upUser
	 * 上传json数据 并返回json数据
	 * 注意实体类必须要有默认的构造函数
	 * @param User
	 * @return
	 */
	@RequestMapping(value = "/upUser", method = RequestMethod.POST)
	@ResponseBody
	public User upUser(@RequestBody User user) {
		user.setName(user.getName()+"=返回");
		return user;
	}

	/**
	 * http://ip:8084/uploadUser
     * 文件上传具体实现方法（单文件上传）
     * 使用postman测试时 选择form-data  不手动添加content-type
     * 
     * 否则会报the request was rejected because no multipart boundary was found错误
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadUser", method = RequestMethod.POST)
    @ResponseBody
    public FileResult upload(@RequestParam("file") MultipartFile file,@RequestParam("name") String name,@RequestParam("id") Integer id) {
        FileResult fileResult=null;
        List<String> fileLists=new ArrayList<>();
    	if (!file.isEmpty()) {
            try {
            	String fileName=file.getOriginalFilename();
            	//文件后缀
            	String suffix=fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	String prefix=fileName.substring(0, fileName.lastIndexOf("."));
            	fileName=prefix+"_"+UUID.randomUUID()+suffix;
            	fileLists.add(fileName);
                // 这里只是简单例子，文件直接输出到项目路径下。
                // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
                // 还有关于文件格式限制、文件大小限制，详见：中配置。
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(createParentFile(),fileName)));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                fileResult=new FileResult(Result.ERROR,e.getLocalizedMessage());
                return fileResult;
            } catch (IOException e) {
            	fileResult=new FileResult(Result.ERROR,e.getLocalizedMessage());
                return fileResult;
            }
            fileResult=new FileResult(fileLists,name,id,Result.SUCCESS);
            return fileResult;
        } else {
        	fileResult=new FileResult(Result.ERROR,"没有上传文件");
            return fileResult;
        }
    }
    
    /**
     * http://ip:8084/uploadsUser
     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadsUser", method = RequestMethod.POST)
    public @ResponseBody FileResult uploads(HttpServletRequest request) {
    	FileResult fileResult=null;
        List<String> fileLists=new ArrayList<>();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String name=request.getParameter("name");
        String id=request.getParameter("id");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                	String Fname=file.getOriginalFilename();
                	//文件后缀
                	String suffix=Fname.substring(Fname.lastIndexOf("."), Fname.length());
                	String prefix=Fname.substring(0, Fname.lastIndexOf("."));
                	Fname=prefix+"_"+UUID.randomUUID()+suffix;
                	fileLists.add(Fname);
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(createParentFile(),Fname)));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    fileResult=new FileResult(Result.ERROR,e.getLocalizedMessage());
                    return fileResult;
                }
            } else {
            	fileResult=new FileResult(Result.ERROR,"没有上传文件");
                return fileResult;
            }
        }
        fileResult=new FileResult(fileLists,name,Integer.parseInt(id),Result.SUCCESS);
        return fileResult;
    }
    
    private File createParentFile() {
    	File file=new File("e:/sptapi/upload/");
    	if(!file.exists() || !file.isDirectory()) {
    		file.mkdirs();
    	}
    	return file;
    }
}
